import { useState, useEffect, useRef } from 'react'

export const useCountDown = () => {
  const itemIdRef = useRef({ id: -1 })
  const [count, setCount] = useState(0)
  const [flog, setFlog] = useState(true)
  const [countText, setCountText] = useState('获取验证码')
  useEffect(() => {
    if (count === 0) {
      setFlog(true)
      setCountText('获取验证码')
      window.clearInterval(itemIdRef.current.id)
    } else {
      setCountText(count + 's获取')
    }
  }, [count])
  const start = (num:number) => {
    if (!flog) return
    setCount(num)
    setFlog(false)
    itemIdRef.current.id = window.setInterval(() => {
      setCount((count) => count - 1)
    }, 1000)
  }
  return { start, count, countText, flog }
}
/*
  start 开启定时器
     - 参数必传 Number
  count 时间展示 Number
  countText 时间文本展示 String
  flog 控制是否禁用 Boolean
*/
